import type { DescrActionType, DescrProps, UseDescrnType } from '../types/descr'
import type { Nullable } from '@/types/global'
import { nextTick, onUnmounted, ref, unref, watch } from 'vue'
import { getDynamicProps } from '@/components/BasicForm/src/common/gloab'

type Props = Partial<DescrProps>

export function useDescr(props?: Props): UseDescrnType {
  const descrRef = ref<Nullable<DescrActionType>>(null)
  const loadedRef = ref<Nullable<boolean>>(false)

  async function getDescr() {
    const desc = unref(descrRef)
    if (!desc) {
      console.error('获取descrRef失败！')
    }
    await nextTick()
    return desc as DescrActionType
  }

  function register(instance: DescrActionType) {
    onUnmounted(() => {
      descrRef.value = null
      loadedRef.value = null
    })
    if (unref(loadedRef) && instance === unref(descrRef)) return
    descrRef.value = instance
    loadedRef.value = true
    watch(
      () => props,
      () => {
        props && instance.setProps(getDynamicProps(props))
      },
      {
        immediate: true,
        deep: true,
      },
    )
  }

  const methods: DescrActionType = {
    setProps: async (formProps: Partial<DescrProps>) => {
      const descr = await getDescr()
      descr.setProps(formProps)
    },
  }
  return [register, methods]
}
